<template>
    <div :class="`tech-shop-order-review ${mode}`">
        <!-- 地址展示、选择 -->
        <ReviewAddress :addressInfo="shopReviewAddress" :mode="mode" :styleMode="styleMode" :theme="theme" />
        <div class="order-review-content">
            <!-- 商品分栏展示 -->
            <div v-for="(item, index) in shopReviewList" :class="`column-content ${index > 0 ? 'have-border' : ''}`" :key="index">
                <div class="store-info">
                    <div class="name-and-select-time">
                        <div class="type-and-name title-color">{{typeValue(item.deliveryType)}}:{{item.warehouseName}}</div>
                        <div class="select-time tip-color" v-if="(isCityType(item) || isPickUpType(item)) && isHaveSelectTime" @click="() => changeDaysValue(item)">{{daysText(item)}}<MiniIcon name="right" :size="16" :mode="mode" :styleMode="styleMode" theme="#7D7D83" /></div>
                    </div>
                    <div class="tip-info" v-if="isPickUpType(item)">最晚取货时间 {{item.warehouseInfo.dead_line_time}}</div>
                </div>
                <div class="product-list">
                    <template v-for="product in item.list">
                        <ReviewGoodsItem
                            :baseInfo="item"
                            :itemInfo="product"
                            :key="product.id"
                            :isDisable="false"
                            :havePickUp="item.isPickUp"
                            :haveExpress="item.isExpress"
                            :haveCity="item.isCity"
                            :deliveryType="item.deliveryType"
                            :isCityBeyond="item.isCityBeyond"
                            :mode="mode"
                            :styleMode="styleMode"
                            :theme="theme"
                            @changeDeliveryType="changeDeliveryType"
                        />
                    </template>
                </div>
                <div v-if="item.isCityRegionLow" class="city-start-price">起送价:<span class="price-label"><span class="label">￥</span>{{item.cityRegionMinPrice}}</span></div>
            </div>
            <template v-if="shopReviewInvalidList.length > 0">
                <div v-for="(item, index) in shopReviewInvalidList" class="column-content" :key="index + 'invalid'">
                    <div class="store-info">
                        <div class="name-and-select-time">
                            <div class="type-and-name">{{typeValue(item.deliveryType)}}:{{item.warehouseName}}</div>
                            <div class="select-time" v-if="(isCityType(item) || isPickUpType(item)) && isHaveSelectTime" @click="() => changeDaysValue(item)">{{daysText(item)}}<MiniIcon name="right" :size="16" :mode="mode" :styleMode="styleMode" theme="#7D7D83" /></div>
                        </div>
                        <div class="tip-info" v-if="isPickUpType(item)">最晚取货时间 {{item.warehouseInfo.dead_line_time}}</div>
                    </div>
                    <div class="product-list">
                        <template v-for="product in item.list">
                            <ReviewGoodsItem
                                :baseInfo="item"
                                :itemInfo="product"
                                :key="product.id"
                                :isDisable="true"
                                :havePickUp="item.isPickUp"
                                :haveExpress="item.isExpress"
                                :haveCity="item.isCity"
                                :deliveryType="item.deliveryType"
                                :isCityBeyond="item.isCityBeyond"
                                :mode="mode"
                                :styleMode="styleMode"
                                :theme="theme"
                                @changeDeliveryType="disableChangeDeliveryType"
                            />
                        </template>
                    </div>
                </div>
            </template>
            <!-- 额外费用 -->
            <ReviewExtCost
                v-if="deliveryPrice"
                :deliveryPrice="deliveryPrice"
                :mode="mode"
                :styleMode="styleMode"
                :theme="theme"
            />
            <!-- 活动优惠 -->
            <!-- <ReviewActivityDiscount v-if="discountPrice" :discount="discountPrice" /> -->
            <div class="discount-cut-line">
                <div class="border-line"></div>
            </div>
            <!-- 优惠信息选择 -->
            <!-- <ReviewDiscount /> -->
            <!-- 总价 -->
            <ReviewTotalPrice
                :discount="discountPrice"
                :price="totalPrice"
                :mode="mode"
                :styleMode="styleMode"
                :theme="theme"
            />
        </div>
        <!-- 会员 -->
        <ReviewMember
            v-if="memberCardInfo"
            :cardInfo="memberCardInfo"
            :isUseMemberPay="isUseMemberPay"
            :isCanChange="!isLowerBalance"
            :mode="mode"
            :styleMode="styleMode"
            :theme="theme"
            @changePayType="changePayType"
        />
        <!-- 备注 -->
        <ReviewRemark
            :mode="mode"
            :styleMode="styleMode"
            :theme="theme"
        />
        <Footer :isHaveBar="true" :mode="mode" :styleMode="styleMode" :theme="theme" />
        <!-- 操作栏 -->
        <ReviewActionBar :isDisable="isCityLow" :price="finalTotalPrice" :discount="discountPrice" @pay="payOrder" :mode="mode" :styleMode="styleMode" :theme="theme" />
        <!-- 更换配送方式弹框 -->
        <!-- 地址选择弹框 -->
        <!-- 修改配送时间 -->
        <ReviewSelectDays
            ref="selectdays"
            :defaultValue="defaultDayValue"
            :length="shopInfoData.booking_days"
            :isSelf="isSelfType"
            :mode="mode"
            :styleMode="styleMode"
            :theme="theme"
            @ensure="ensureChagneDays"
        />
        <!-- 选择支付方式 -->
        <ReviewChoosePayment ref="choosePayment" :defaultVal="paytype" @ensure="paymentResult" :mode="mode" :theme="theme" :styleMode="styleMode" />
        <!-- 密码认证 -->
        <ShopMemberPassword ref="authModal" @ensure="authPasswordResult" @cancel="gotoShopOrderList" :mode="mode" :theme="theme" :styleMode="styleMode" />
    </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { MiniIcon } from '@components/base';
import { Footer } from '@components/biz';
import ReviewGoodsItem from './review/ReviewGoodsItem';
import ReviewAddress from './review/ReviewAddress';
import ReviewExtCost from './review/ReviewExtCost';
import ReviewActivityDiscount from './review/ReviewActivityDiscount';
import ReviewDiscount from './review/ReviewDiscount';
import ReviewTotalPrice from './review/ReviewTotalPrice';
import ReviewMember from './review/ReviewMember';
import ReviewRemark from './review/ReviewRemark';
import ReviewActionBar from './review/ReviewActionBar';
import ReviewSelectDays from './review/ReviewSelectDays';
import ReviewChoosePayment from './review/ReviewChoosePayment';
import ShopMemberPassword from './components/ShopMemberPassword';

import { redirectTo, repalceTo, setTitle } from '@common/utils';
import { calcAllReviewPrice, chagneTimeDaysValue, chagneProductDeliveryType,
    reviewDataToOrderData, reviewBagListData, getIsLowCityExpress, getMinCityExpressPrice, getDayText } from '@biztools/shopReview';
import { SHOP_MODE_TYPE } from '@constants/shop';
import { autoShopPayment } from '@common/environment';
import { getUiMode, getUiTheme, getUiStyleMode } from '@biztools/info';
import { platformTruth } from '@common/environment';
import { invokeGotoMiniShopStatus } from '@common/pay/wechat_mini';
import { DEFAULT_MODE, DEFAULT_THEME, DEFAULT_STYLE_MODE } from '@constants/style';
import { DELIVERY_TYPE, DELIVERY_TYPE_SHORT_TEXT, SHOP_TRADE_CHANNEL } from '@constants/shop';
import { PAY_TYPE_MEMBERCARD, PAY_TYPE_WECHAT, PAY_TYPE_ALIPAY, SHOP_ORDER_PAY_TYPE_VALUE } from '@constants/pay';
// mock
import logger from '@common/logger';
import { ClearTip, Tip, TipError, TipLoading } from '@common/tip';
import { MEMBER_BIZ_TYPE } from '@constants/member';
export default {
    name: 'ShopOrderReview', // 确认订单
    components: {
        MiniIcon,
        Footer,
        ReviewGoodsItem,
        ReviewAddress,
        ReviewExtCost,
        ReviewActivityDiscount,
        ReviewDiscount,
        ReviewTotalPrice,
        ReviewMember,
        ReviewRemark,
        ReviewActionBar,
        ReviewSelectDays,
        ReviewChoosePayment,
        ShopMemberPassword,
    },
    data() {
        return {
            totalPrice: 0,
            discountPrice: 0,
            deliveryPrice: 0,
            // 默认值-选择时间
            defaultDayValue: -1,
            // 修改的项
            editListItem: null,
            isSelfType: true,
            // // 结算价格
            // finalTotalPrice: 0,
            // memberCardInfo: {},
            // 支付方式
            paytype: PAY_TYPE_MEMBERCARD,
            // 会员卡支付参数
            memberPayParams: null,
            // 获取设置的配置信息
            mode: getUiMode() || DEFAULT_MODE,
            theme: getUiTheme() || DEFAULT_THEME,
            styleMode: getUiStyleMode() || DEFAULT_STYLE_MODE,
        };
    },
    computed: {
        ...mapState({
            shopInfoData: state => state.shop.shopInfoData,
            shopReviewAddress: state => state.shopReview.shopReviewAddress,
            shopReviewList: state => state.shopReview.shopReviewList,
            shopReviewInvalidList: state => state.shopReview.shopReviewInvalidList,
            shopRequestId: state => state.shopReview.shopRequestId,
            shopReviewRemark: state => state.shopReview.shopReviewRemark,
            memberInfo: state => state.shopMember.memberInfo,
            memberCardInfo: state => state.shopMember.memberCard,
        }),
        typeValue() {
            return item => DELIVERY_TYPE_SHORT_TEXT[item];
        },
        // 最终结算价格
        finalTotalPrice() {
            return this.totalPrice - this.discountPrice;
        },
        isExpressType() {
            return item => {
                const { deliveryType } = item;
                return deliveryType === DELIVERY_TYPE.EXPRESS;
            };
        },
        isCityType() {
            return item => {
                const { deliveryType } = item;
                return deliveryType === DELIVERY_TYPE.CITY_EXPRESS;
            };
        },
        isPickUpType() {
            return item => {
                const { deliveryType } = item;
                return deliveryType === DELIVERY_TYPE.SELF_PICK_UP;
            };
        },
        isBrandMode() {
            return this.shopInfoData.operation_mode === SHOP_MODE_TYPE.brand;
        },
        // 是否可选预约时间
        isHaveSelectTime() {
            const { booking_days } = this.shopInfoData;
            return booking_days > 0;
        },
        // 时间提示
        daysText() {
            return item => {
                let text = '选择时间';
                const { deliveryType, timeDays } = item;
                if (timeDays === -1) {
                    return '选择时间';
                }
                if (deliveryType === DELIVERY_TYPE.SELF_PICK_UP) {
                    return `预计${getDayText(timeDays)}自提`;
                }
                if (deliveryType === DELIVERY_TYPE.CITY_EXPRESS) {
                    return `预计${getDayText(timeDays)}送达`;
                }
            };
        },
        isUseMemberPay() {
            return this.paytype === PAY_TYPE_MEMBERCARD;
        },
        // 是否是余额不足
        isLowerBalance() {
            return this.memberCardInfo.balance < this.finalTotalPrice;
        },
        isCityLow() {
            const arr = this.shopReviewList.filter(item => item.isCityRegionLow);
            return arr.length > 0;
        },
    },
    watch: {
        shopReviewList(list, oldList) {
            // 计算价格
            this.calcPrice(list);
        },
        finalTotalPrice(val, oldVal) {
            this.changePayType(!this.isLowerBalance);
        },
    },
    async mounted() {
        setTitle('确认订单');
        TipLoading('加载中...');
        const flag = await this.getRequestId();
        if (flag) {
            // TODO:存在RequestId
        }
        // 刷新当前的列表仓库信息
        await this.refreshReviewListWarehouseInfo(this.isBrandMode);
        // 获取用户信息
        await this.getShopMemberInfo();
        this.calcPrice();
        this.changePayType(this.memberCardInfo ? !this.isLowerBalance : false);
        ClearTip();
    },
    methods: {
        ...mapActions([
            'getShopMemberInfo',
            'getRequestId',
            'clearRequestId',
            'changeShopReviewList',
            'changeInvalidReviewList',
            'createShopUniteOrder',
            'payShopUniteOrder',
            'refreshReviewListWarehouseInfo',
            'deleteOnlineShopBagData',
            'changeShopReviewRemark',
        ]),
        // 选择时间
        changeDaysValue(item) {
            this.isSelfType = this.isPickUpType(item);
            this.defaultDayValue = item.timeDays;
            this.editListItem = item;
            this.$refs.selectdays.show();
        },
        // 确认修改时间
        ensureChagneDays(value) {
            // 修改时间
            const list = chagneTimeDaysValue(this.shopReviewList, this.editListItem, value);
            logger.info('ShopReview => 修改时间的结果为：', list);
            this.changeShopReviewList({list, isMain: this.isBrandMode});
        },
        // 修改配送方式
        changeDeliveryType({ type, info, product }) {
            logger.info('ShopOrderReview => 修改配送方式', type, info, product);
            const list = chagneProductDeliveryType([...this.shopReviewList, ...this.shopReviewInvalidList], info, product, type);
            this.changeInvalidReviewList([]);
            logger.info('ShopOrderReview => 修改配送方式结果：', list);
            this.changeShopReviewList({list, isMain: this.isBrandMode});
        },
        // disableChangeDeliveryType
        disableChangeDeliveryType({ type, info, product }) {
            logger.info('ShopOrderReview => 修改配送方式', type, info, product);
            const list = chagneProductDeliveryType([...this.shopReviewList, ...this.shopReviewInvalidList], info, product, type);
            this.changeInvalidReviewList([]);
            logger.info('ShopOrderReview => 修改配送方式结果：', list);
            this.changeShopReviewList({list, isMain: this.isBrandMode});
        },
        // 弹窗修改支付方式
        async paymentResult(type) {
            this.memberPayParams = {
                ...this.memberPayParams,
                pay_method: SHOP_ORDER_PAY_TYPE_VALUE[type],
            };
            await this.orderPayAction();
        },
        // 会员按钮修改支付方式
        changePayType(isUseMember) {
            const { isWechat, isWechatMini } = platformTruth();
            // 是否使用会员卡
            if (isUseMember) {
                this.paytype = PAY_TYPE_MEMBERCARD;
            } else {
                this.paytype = isWechat || isWechatMini ? PAY_TYPE_WECHAT : PAY_TYPE_ALIPAY;
            }
        },
        // 下单并支付
        async payOrder() {
            const { isToutiaoMini, isWechatMini } = platformTruth();
            TipLoading('订单创建中...');
            // 转换订单数据
            const orders = reviewDataToOrderData(this.shopReviewList, this.isBrandMode);
            if (orders.length === 0) {
                Tip('无有效订单，请检查');
                return;
            }
            const targetList = reviewBagListData(this.shopReviewList);
            logger.info('ShopReview => 当前地址为', this.shopReviewAddress);
            // 判断是否必须要收货地址
            let addressInfo = {};
            if (this.isNeedAddress()) {
                // 必须有地址
                addressInfo = this.getAddressInfo();
                if (!addressInfo) {
                    Tip('请先选择地址');
                    return;
                }
            }
            const params = {
                request_id: this.shopRequestId,
                address_info: {
                    ...addressInfo,
                },
                orders,
                remark: this.shopReviewRemark || '',
                // 会员卡信息，后续改为从 SDK 获取
                card_info: this.memberCardInfo ? {
                    group_id: this.memberCardInfo.groupId,
                    grade_id: this.memberCardInfo.gradeId,
                    grade_name: this.memberCardInfo.gradeName,
                    phone: this.memberInfo.mobile,
                } : {},
                pay_info: {
                    discount: this.discountPrice,
                    trans: this.finalTotalPrice,
                }
            };
            try {
                const res = await this.createShopUniteOrder(params);
                logger.success('ShopReview => 组合下单结果：', res);
                if (res) {
                    // 清除购物车
                    await this.deleteOnlineShopBagData(targetList);
                    // 清空备注
                    this.changeShopReviewRemark('');
                    logger.success('ShopReview => 清除购物车数据：');
                    if (this.paytype !== PAY_TYPE_MEMBERCARD && isToutiaoMini) {
                        // 不是卡支付、选择支付平台
                        this.memberPayParams = {
                            biz_request_no: this.shopRequestId,
                            trade_channel: SHOP_TRADE_CHANNEL,
                        };
                        ClearTip();
                        this.$refs.choosePayment.show();
                    } else {
                        this.memberPayParams = {
                            biz_request_no: this.shopRequestId,
                            pay_method: SHOP_ORDER_PAY_TYPE_VALUE[this.paytype],
                            trade_channel: SHOP_TRADE_CHANNEL,
                        };
                        // 判断是否是免密
                        if (!this.memberInfo.openNosecret && this.paytype === PAY_TYPE_MEMBERCARD) {
                            logger.success('ShopReview => 开始认证密码');
                            // 打开密码框
                            ClearTip();
                            this.$refs.authModal.show();
                        } else {
                            await this.orderPayAction();
                        }
                    }
                }
            } catch(err) {
                TipError('下单失败，请重试');
            }
        },
        async authPasswordResult(flag) {
            if (flag) {
                await this.orderPayAction();
            } else {
                setTimeout(() => {
                    this.$refs.authModal.show();
                    // TipError('密码认证失败，请重试。');
                }, 3100);
            }
        },
        // 执行会员卡支付逻辑
        async orderPayAction() {
            const { isWechatMini } = platformTruth();
            // 下单成功，直接调用支付
            const prepayRes = await this.payShopUniteOrder(this.memberPayParams);
            logger.success('ShopReview => 创建预支付单', prepayRes);
            if (prepayRes) {
                this.clearRequestId();
                if (prepayRes.status !== 0) {
                    isWechatMini ? this.gotoWechatMiniNoticePage() : this.gotoShopOrderList();
                    ClearTip();
                } else {
                    autoShopPayment(prepayRes.prepay_info, '', (flag) => {
                        // 支付成功后的回调
                        logger.success('自动支付后的回调函数，返回结果为：', flag);
                        ClearTip();
                        this.gotoShopOrderList();
                    });
                }
            }
        },
        gotoShopOrderList() {
            // 清除，购物车下单的额菜品
            repalceTo('shop-order/list');
        },
        gotoWechatMiniNoticePage() {
            invokeGotoMiniShopStatus();
        },
        isNeedAddress() {
            const list = this.shopReviewList.filter(item => item.deliveryType !== DELIVERY_TYPE.SELF_PICK_UP);
            return list.length > 0;
        },
        getAddressInfo() {
            // address: "浙江省杭州市余杭区文一西路和常二路交叉口富力天贸广场26号楼"
            // building_number: "123123"
            // city_code: 156330100
            // contact: "123"
            // gender: "先生"
            // id: 168
            // latitude: 30.28142
            // longitude: 120.01738
            // mobile: "18899990000"
            // tag: "家"
            if (this.shopReviewAddress) {
                return {
                    city_code: this.shopReviewAddress.city_code + '',
                    lat: this.shopReviewAddress.latitude,
                    lng: this.shopReviewAddress.longitude,
                    contact: this.shopReviewAddress.contact,
                    mobile: this.shopReviewAddress.mobile,
                    address: `${this.shopReviewAddress.address}${this.shopReviewAddress.building_number}`,
                };
            } else {
                return false;
            }
        },
        // 计算所有价格
        calcPrice(list) {
            const _list = list || this.shopReviewList;
            const info = calcAllReviewPrice(_list);
            logger.info('ShopRevie => 计算后的价格为：', info);
            this.totalPrice = info.totalPrice;
            this.deliveryPrice = info.deliveryPrice;
        },
    },
};
</script>

<style lang="less">
.tech-shop-order-review {
    .mode-white();
    &.white {
        background-color: @shop-bg-color;
    }
    &.black {
        background-color: #000000;
        .discount-cut-line {
            .card-circle-border-h(@gap-md, 7px, 7px, #000);
            .border-line {
                background-color: rgba(125,125,131,0.2);
            }
        }
        .order-review-content {
            background-color: @black-bg-color;
        }
        .order-review-content {
            .discount-cut-line {
                .card-circle-border-h(13px, 6px, 6px, @black);
                .border-line {
                    background-color: @tip-color !important;
                    opacity: .2;
                }
            }
        }
    }
    .city-start-price {
        font-size: @font-size;
        color: @red;
        .price-label {
            font-weight: 500;
            font-family: @font-family-number;
            .label {
                .m-r(-2);
            }
        }
    }
    .order-review-content {
        .m-h(@shop-bag-gap);
        // .p-v(@shop-bag-gap);
        background-color: @white;
        border-radius: @border-radius;
        .column-content {
            .p(@shop-bag-gap);
            &.have-border {
                .shop-border-line();
            }
            .store-info {
                .flex-column();
                .name-and-select-time {
                    .flex();
                    justify-content: space-between;
                    .type-and-name {
                        font-size: @font-size;
                        font-weight: 500;
                        line-height: 1;
                    }
                    .select-time {
                        color: @tip-color;
                        font-size: @shop-font-size;
                        line-height: @shop-font-size;
                        .flex();
                        align-items: center;
                        .mini-icon {
                            opacity: .7;
                        }
                    }
                }
                .tip-info {
                    font-size: @shop-font-size-sm;
                    color: @tip-color;
                    opacity: .7;
                    .m-t(@shop-gap-sm);
                }
            }
        }

        .discount-cut-line {
            // background-color: aqua;
            .m-t(@gap-sm);
            height: 1px;
            .p-h(@gap-md);
            // .card-circle-border-h(13px, 6px, 6px, @shop-bg-color);
            .border-line {
                .m-b(10px);
                height: 1px;
                background-color: @border-color;
                width: 100%;
            }
        }
    }
}
</style>
